package com.sywb.chuangyebao.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import org.bining.footstone.BaseConstants;

import java.text.DecimalFormat;

/**
 * 处理double格式的工具类
 */
public class DoubleFormatUtil {
    /**
     * 设置限制输入小数位数
     *
     * @param editText 需要设置的editttext
     * @param num      限制输入小数位数
     */
    public static void setPointNum(final EditText editText, final int num) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(BaseConstants.DOT)) {
                    if (s.length() - 1 - s.toString().indexOf(BaseConstants.DOT) > num) {
                        s = s.toString().subSequence(0, s.toString().indexOf(BaseConstants.DOT) + num + 1);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().equals(BaseConstants.DOT)) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(num);
                }

                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(BaseConstants.DOT)) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }

        });
    }

    /**
     * 对double多位数进行处理，并保留两位小数
     *
     * @param value 需要格式化的数，如价格
     */
    public static String formatDoubleNumber(double value) {
        if (value != 0.00) {
            java.text.DecimalFormat df = new java.text.DecimalFormat("######0.00");
            return df.format(value);
        } else {
            return "0.00";
        }
    }

    /**
     * 对double小数进行去除0操作
     */
    public static String formatDoubleToString(double number) {
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        return decimalFormat.format(number);
    }

}
